﻿using Rewired;
using UnityEngine;

public class CubeRotate : MonoBehaviour {

    public float rotateSpeed = 1f;

    private void OnEnable()
    {
        if (!ReInput.isReady) return;

        Player player = ReInput.players.GetPlayer(0);
        if (player == null) return;

        // Subscribe to input events
        player.AddInputEventDelegate(OnRotationReceivedX, UpdateLoopType.Update, InputActionEventType.AxisActive, "Horizontal");
        player.AddInputEventDelegate(OnRotationReceivedX, UpdateLoopType.Update, InputActionEventType.AxisInactive, "Horizontal");
        player.AddInputEventDelegate(OnRotationReceivedY, UpdateLoopType.Update, InputActionEventType.AxisActive, "Vertical");
        player.AddInputEventDelegate(OnRotationReceivedY, UpdateLoopType.Update, InputActionEventType.AxisInactive, "Vertical");
    }

    private void OnDisable()
    {
        if (!ReInput.isReady) return;

        Player player = ReInput.players.GetPlayer(0);
        if (player == null) return;

        // Unsubscribe from input events
        player.RemoveInputEventDelegate(OnRotationReceivedX);
        player.RemoveInputEventDelegate(OnRotationReceivedY);
    }

    private void OnRotationReceivedX(InputActionEventData data)
    {
        OnRotationReceived(new Vector2(data.GetAxis(), 0f));
    }

    private void OnRotationReceivedY(InputActionEventData data)
    {
        OnRotationReceived(new Vector2(0f, data.GetAxis()));
    }

    private void OnRotationReceived(Vector2 rotate)
    {
        rotate *= rotateSpeed;
        transform.Rotate(Vector3.up, -rotate.x, Space.World);
        transform.Rotate(Vector3.right, rotate.y, Space.World);
    }
}
